package org.osami.commons.dialog.android.androiddisplayservice;

import android.R;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.view.KeyEvent;

import com.prosyst.mbs.android.application.ActivityWrapper;
import com.prosyst.mbs.android.application.ApplicationFactory;
import com.prosyst.mbs.android.application.CallbackHandler;

import org.osami.commons.dialog.IDisplayService;

public class MyApplicationFactory implements ApplicationFactory, IDisplayService  {
	private static final String MY_OSGI_ANDROID_APP = "OSAmI Display Service";
	static final String MY_OSGI_VIEW = "org.osami.commons.dialog.android.view";
	private Bitmap icon;
	private ActivityWrapper context = null;
	private CallbackHandler handler = null;
	private MyView view = null;
	private int selection = -1;
	
	NotificationManager mNotificationManager;
	Notification notification = null;
	
	public ActivityWrapper getContext() {
		return context;
	}
	
	synchronized int getSelection() {
		return selection;
	}
	
	synchronized void setSelection(int selection) {
		this.selection = selection;
	}

	public View createView(ActivityWrapper context, Intent starter, CallbackHandler callbackHandler) {
		this.context = context;
		
		Log.i(Activator.tag(), "Creating view");
		
//		EditText myView = new EditText(context) {
//			
//			public boolean onKeyDown(int keyCode, KeyEvent event) {
//				if (keyCode == KeyEvent.KEYCODE_BACK) {
//					showMessage("TESTI", MyApplicationFactory.this.context);
//					MyApplicationFactory.this.handler.closeActivity(null);
//					return true;
//				} else {
//					return super.onKeyDown(keyCode, event);
//				}
//			}
//			
//		};
		
		view = new MyView(context, this);
		
		Log.i(Activator.tag(), "Creating notification");
		
		String ns = Context.NOTIFICATION_SERVICE;
		/*NotificationManager*/ mNotificationManager = (NotificationManager)context.getSystemService(ns);
		
		int icon = R.drawable.arrow_down_float;
		CharSequence tickerText = "OSAmI Message";
		long when = System.currentTimeMillis();

		/*Notification*/ notification = new Notification(icon, tickerText, when);
		
		notification.defaults |= Notification.DEFAULT_SOUND;
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		Context appContext = context.getApplicationContext();
		CharSequence contentTitle = "OSAmI DisplayService";
		CharSequence contentText = "Received message";
		Intent notificationIntent = new Intent();
		//notificationIntent.setComponent(new ComponentName("com.prosyst.mbs.mobile.android", "com.prosyst.mbs.android.applications.OSGiPrograms"));
		notificationIntent.setAction("com.prosyst.mbs.APPLICATION");
		notificationIntent.putExtra("mbs.android.application.type", "org.osami.commons.dialog.android.view");
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

		notification.setLatestEventInfo(appContext, contentTitle, contentText, contentIntent);
		
		
		//mNotificationManager.notify(1, notification);
		
		Log.i(Activator.tag(), "Notification created");
		
		return view;
	}
	
	// This method provides a custom icon to represent the UI of this bundle
	public Bitmap getIcon() {
		if (icon == null) {
			//icon = BitmapFactory.decodeStream(MyOSGiAndroidApp.class.getResourceAsStream("/resources/48-star-cold.png"));
		}
		return icon;
	}
	
	// This method specifies the main application type of the bundle
	public String getMainType() {
		return MY_OSGI_VIEW;
	}
	
	 //This method specifies the friendly name of this bundle. It will be available in 
	// the Android desktop under this name.
	public String getName() {
		return MY_OSGI_ANDROID_APP;
	}
	
	// This method returns the main application types supported by this bundle.
	public String[] getSuportedTypes() {
		return new String[] {MY_OSGI_VIEW};
	}
	
	public void showQuestion(String msg, String [] options, ActivityWrapper context) {
		Log.i(Activator.tag(), "Showing question " + msg + ", num options = " + options.length);
		for (int i = 0; i < options.length; i++)
			Log.i(Activator.tag(), "option " + i + ": " + options[i]);
		
		if (null == context) {
			Log.i(Activator.tag(), "Can't show question since context not defined");
			return;
		}
		
		// For some reason the code below doesn't work (the list won't be displayed)
		// We shall use a quick and dirty solution and provide a dialog for two options using buttons.
		// TODO: Fix this (sure!)
		/*
		boolean [] checkedItems = new boolean[options.length];
		for (int i = 0; i < checkedItems.length; i++)
			checkedItems[i] = false;
		Builder msgBox = new AlertDialog.Builder(context).setMessage(msg)
		.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int button) {
				dialog.dismiss();
			}
		})
		.setMultiChoiceItems(options, null, new DialogInterface.OnMultiChoiceClickListener() {
			
			public void onClick(DialogInterface dialog, int arg1, boolean arg2) {
				dialog.dismiss();
				
			}
		});
		*/
		
		if (2 == options.length) {
			Builder msgBox = new AlertDialog.Builder(context)
			.setCancelable(false)
			.setTitle("Question")
			.setMessage(msg)
			.setPositiveButton(options[0], new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int button) {
					setSelection(0);
					dialog.dismiss();
				}
			})
			.setNegativeButton(options[1], new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int button) {
					setSelection(1);
					dialog.dismiss();
				}
			});
			
			msgBox.show();
		}
	}
	
	public void showMessage(String msg, ActivityWrapper context) {
		Log.i(Activator.tag(), "Showing message");
		
		if (null == context) {
			Log.i(Activator.tag(), "Can't show message since context not defined");
			return;
		}
		
		Builder msgBox = new AlertDialog.Builder(context)
		.setCancelable(false)
		.setTitle("Message")
		.setMessage(msg)
		.setPositiveButton("Dismiss", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int button) {
				dialog.dismiss();
			}
		});
		
		msgBox.show();
	}
	
	public int display(String text, String[] options) {
		Log.i(Activator.tag(), "Handling display invocation");
		boolean isMessage = (null == options || options.length < 1);
		
		if (notification != null) {
			Log.i(Activator.tag(), "Creating notification");
			
			if (isMessage)
				notification.setLatestEventInfo(context.getApplicationContext(), "Message", text, notification.contentIntent);
			else
				notification.setLatestEventInfo(context.getApplicationContext(), "Question", text, notification.contentIntent);
			
			try {			
				mNotificationManager.notify(1, notification);
				}
			catch (Exception E) {
				
				}
				
			
		} else {
			Log.i(Activator.tag(), "Context not defined");
		}
		
		if (null != view) {
			Log.i(Activator.tag(), "Notification view found");	
			while (!view.isShown()) {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
			
			if (isMessage) { // message
				Log.i(Activator.tag(), "Message");
				Message msg = Message.obtain(view.getMessageHandler(), MyView.WHAT_MESSAGE, text);
				view.getMessageHandler().sendMessage(msg);
			} else { // question
				setSelection(-1);
				Log.i(Activator.tag(), "Question");
				Question question = new Question(text, options);
				Message msg = Message.obtain(view.getMessageHandler(), MyView.WHAT_QUESTION, question);
				view.getMessageHandler().sendMessage(msg);
				
				// Not the most elegant solution but avoids using split face since android
				// doesn't provide synchronous dialogs
				Log.i(Activator.tag(), "Entering sleep loop to wait user input...");
				while (-1 == getSelection()) {
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						Log.i(Activator.tag(), "Error");
					}
				}
				
				Log.i(Activator.tag(), "User input detected, selection = " + getSelection());
				return selection;
			}
		} else {
			Log.i(Activator.tag(), "Notification view NOT found");
		}
			
		
		return 0;
	}

	private void startActivity(Intent intent) {
		// TODO Auto-generated method stub
		
	}

}
